package com.youlai.system.controller;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.youlai.system.common.constant.SystemConstants;
import com.youlai.system.common.model.Option;
import com.youlai.system.common.result.PageResult;
import com.youlai.system.common.result.Result;
import com.youlai.system.model.form.QuestionForm;
import com.youlai.system.model.query.QuestionPageQuery;
import com.youlai.system.model.vo.QuestionPageVO;
import com.youlai.system.model.vo.QuestionScoreCountVO;
import com.youlai.system.plugin.dupsubmit.annotation.PreventDuplicateSubmit;
import com.youlai.system.service.SysDictService;
import com.youlai.system.service.SysQuestionService;
import com.youlai.system.service.SysScoreService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 问题分类控制器
 */
@Tag(name = "12.问题分类接口")
@RestController
@RequestMapping("/api/v1/questions")
@RequiredArgsConstructor
public class SysQuestionController {

    private final SysQuestionService questionService;

    private final SysScoreService scoreService;

    private final SysDictService dictService;

    @Operation(summary = "问题分类分页列表")
    @GetMapping("/page")
    public PageResult<QuestionPageVO> getQuestionPage(
            @ParameterObject QuestionPageQuery queryParams
    ) {
        IPage<QuestionPageVO> result = questionService.getQuestionPage(queryParams);
        Map<Long, QuestionScoreCountVO> questionScoreCountMap = scoreService.getAllQuestionScoreCountMap();
        result.getRecords().forEach(questionPageVO -> {
            QuestionScoreCountVO questionScoreCountVO = questionScoreCountMap.get(questionPageVO.getId());
            if (questionScoreCountVO != null) {
                questionPageVO.setTotalCount(questionScoreCountVO.getTotalCount());
                questionPageVO.setSuccessCount(questionScoreCountVO.getSuccessCount());
                questionPageVO.setFailCount(questionScoreCountVO.getFailCount());
                questionPageVO.setSuccessRate(questionScoreCountVO.getSuccessRate());
            }

            questionPageVO.setQuotaLabel(dictService.getLabel(SystemConstants.Quota, questionPageVO.getQuota()));
        });
        return PageResult.success(result);
    }

    @Operation(summary = "新增问题分类")
    @PostMapping
    @PreAuthorize("@ss.hasPerm('sys:question:add')")
    @PreventDuplicateSubmit
    public Result saveQuestion(
            @RequestBody @Valid QuestionForm questionForm
    ) {
        boolean result = questionService.saveQuestion(questionForm);
        return Result.judge(result);
    }

    @Operation(summary = "问题分类表单数据")
    @GetMapping("/{questionId}/form")
    public Result<QuestionForm> getQuestionForm(
            @Parameter(description = "问题分类ID") @PathVariable Long questionId
    ) {
        QuestionForm formData = questionService.getQuestionForm(questionId);
        return Result.success(formData);
    }


    @Operation(summary = "修改问题分类")
    @PutMapping(value = "/{questionId}")
    @PreAuthorize("@ss.hasPerm('sys:question:edit')")
    public Result updateQuestion(
            @Parameter(description = "问题分类ID") @PathVariable Long questionId,
            @RequestBody @Validated QuestionForm questionForm) {
        boolean result = questionService.updateQuestion(questionId, questionForm);
        return Result.judge(result);
    }

    @Operation(summary = "删除问题分类")
    @DeleteMapping("/{ids}")
    @PreAuthorize("@ss.hasPerm('sys:question:delete')")
    public Result deleteQuestions(
            @Parameter(description = "问题分类ID，多个以英文逗号(,)分割") @PathVariable String ids
    ) {
        Assert.isTrue(StrUtil.isNotBlank(ids), "问题分类删除数据为空");
        List<Long> idList = Arrays.stream(ids.split(",")).map(Long::parseLong).collect(Collectors.toList());
        boolean questionHasUsed = scoreService.questionHasUsed(idList);
        Assert.isTrue(!questionHasUsed, "问题分类使用中，不能被删除");
        boolean result = questionService.deleteQuestions(idList);
        return Result.judge(result);
    }

    @Operation(summary = "问题分类下拉列表")
    @GetMapping("/options")
    public Result<List<Option>> listQuestionOptions(@RequestParam(value = "quota", required = false) Integer quota) {
        List<Option> list = questionService.listQuestionOptions(quota);
        return Result.success(list);
    }
}
